package com.utils.wifi

import android.content.Context
import android.content.IntentFilter
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.Build

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 2021/6/17
 */
class WifiImpl:IWifi {
    override fun openWifi(context: Context) {
        val wifiManager =
                context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        wifiManager.isWifiEnabled = true
    }

    override fun connectWifi(context: Context, ssid: String, pwd: String) {
        val wifiManager =
                context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val config = WifiConfiguration()
        config.allowedAuthAlgorithms.clear()
        config.allowedGroupCiphers.clear()
        config.allowedKeyManagement.clear()
        config.allowedPairwiseCiphers.clear()
        config.allowedProtocols.clear()

        config.SSID = "\"$ssid\""
        config.preSharedKey = "\"$pwd\""
        config.hiddenSSID = true
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN)
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP)
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
        config.allowedProtocols.set(WifiConfiguration.Protocol.RSN)
        config.allowedProtocols.set(WifiConfiguration.Protocol.WPA)
        config.status = WifiConfiguration.Status.ENABLED
        val addNetworkId = wifiManager.addNetwork(config)
        if (addNetworkId==-1){
            WifiUtils.wifiStateCallBack?.get()?.onConnectedFail()
            return
        }
        wifiManager.enableNetwork(addNetworkId, true)
    }

    override fun registerWifiStateChangerReceiver(context: Context, receiver: WifiConnectReceiver, wifiStateCallBack: WifiStateCallBack) {
        val intentFilter = IntentFilter()
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
        //安卓Q以下通过广播来监听连接结果
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
        context.registerReceiver(receiver, intentFilter)
    }

    override fun unregisterWifiStateChangeReceiver(context: Context, receiver: WifiConnectReceiver?) {
        //nothing to do
    }
}